import { useEffect, useState } from 'react';
import http from '../services/api';
import { TaskInfo, ImageResult } from '../types/components/homepage';
import './HomePage.css';
import { ImageGenerationResult } from '../types/api/image';
import { Empty } from 'antd'; // 引入 Ant Design 的 Empty 组件

export default function HomePage() {
  const [images, setImages] = useState<ImageResult[]>([]);
  const [taskInfo, setTaskInfo] = useState<TaskInfo | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [selectedImage, setSelectedImage] = useState<string | null>(null); // 当前选中的图片URL

  useEffect(() => {
    // 初次加载时检查sessionStorage
    const initialTaskId = sessionStorage.getItem('task_id');
    if (initialTaskId) {
      fetchImages(initialTaskId); // 初次加载时检查sessionStorage，如果有task_id则直接加载
    }

    // 添加当前标签页的task_id变化监听
    const handleTaskIdChange = () => {
      const taskId = sessionStorage.getItem('task_id');
      if (taskId) {
        fetchImages(taskId); // 直接调用 fetchImages，移除 setTimeout
      }
    };

    // 监听自定义事件
    window.addEventListener('taskIdChanged', handleTaskIdChange);

    return () => {
      // window.removeEventListener('storage', handleStorageChange);
      window.removeEventListener('taskIdChanged', handleTaskIdChange);
    };
  }, []);

  const fetchImages = async (taskId: string) => {
    try {
      setIsLoading(true); // 确保轮询开始时设置加载状态
      const poll = async () => {
        const response = await http.get<ImageGenerationResult>(`/tasks/${taskId}`, {
          headers: {
            'Authorization': `Bearer ${import.meta.env.VITE_API_KEY}`
          }
        });
        const data = response;

        if (data.output.results && data.output.results.length > 0) {
          // 图像生成完成，更新状态
          setTaskInfo({
            submitTime: data.output.submit_time,
            endTime: data.output.end_time
          });
          setImages(data.output.results);
          setIsLoading(false); // 图像加载完成，关闭加载状态
        } else {
          // 图像未生成完成，继续轮询
          setTimeout(poll, 2000); // 每 2 秒检查一次
        }
      };

      poll(); // 开始轮询
    } catch (error) {
      console.error('Error fetching images:', error);
      setIsLoading(false); // 发生错误时，关闭加载状态
    }
  };

  // 处理图片点击事件
  const handleImageClick = (url: string) => {
    setSelectedImage(url);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setSelectedImage(null);
  };

  // 下载图片
  const handleDownload = (url: string) => {
    const link = document.createElement('a');
    link.href = url;
    link.download = `generated-image-${Date.now()}.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return (
    <div className="home-page">
      {isLoading ? (
        <div className="loading-indicator">
          <div className="loading-spinner"></div>
          <div className="loading-text">正在生成，请稍候...</div>
        </div>
      ) : (
        <>
          {taskInfo && (
            <div className="task-info">
              <span className="task-time">提交时间: {taskInfo.submitTime}</span>
              <span className="task-separator">|</span>
              <span className="task-time">完成时间: {taskInfo.endTime}</span>
            </div>
          )}

          <div className="image-grid">
            {images && images.length > 0 ? (
              images.map((image, index) => (
                <div key={index} className="image-container">
                  <img
                    src={image.url}
                    alt={`Generated image ${index + 1}`}
                    className="image-item"
                    onClick={() => handleImageClick(image.url)}
                  />
                  <div
                    className="download-icon"
                    onClick={() => handleDownload(image.url)}
                  >
                    ⬇️
                  </div>
                </div>
              ))
            ) : (
              <div className="no-images">
                <Empty
                  description="在左侧输入你的想法，开始创作吧"
                />
              </div>
            )}
          </div>

          {/* 图片弹窗 */}
          {selectedImage && (
            <div className="image-modal" onClick={handleCloseModal}>
              <div className="modal-content" onClick={(e) => e.stopPropagation()}>
                <img src={selectedImage} alt="Preview" className="modal-image" />
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}
